<template>
  <div>
    <!-- 操作按钮区 -->
    <el-row :gutter="20" style="margin-bottom: 16px;">
      <el-col>
        <!-- 新增按钮 -->
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <!-- 批量删除按钮 -->
        <el-button type="danger" :disabled="selectedRows.length === 0" @click="">删除</el-button>
        <!-- 刷新按钮，重新获取表格数据 -->
        <el-button icon="el-icon-refresh" @click="shuxian()">刷新</el-button>
        <!-- 配置按钮，弹出列显示配置弹窗 -->
        <el-button icon="el-icon-setting" @click="showColumnConfig = true">配置</el-button>
        <!-- 更多查询按钮，显示/隐藏更多查询条件 -->
        <el-button icon="el-icon-filter" @click="showMoreQuery = !showMoreQuery">
          更多查询
        </el-button>
      </el-col>
    </el-row>
    <!-- 更多查询条件区域 -->
    <el-row v-if="showMoreQuery" :gutter="20" style="margin-bottom: 16px;">
      <el-col>
        <!-- 这里是每个查询条件的输入框 -->
        <el-input v-model="page.GoodsName" placeholder="商品名称" style="width: 160px; margin-right: 8px;" />
        <el-input v-model="page.Batch" placeholder="生产批次" style="width: 160px; margin-right: 8px;" />
        <el-input v-model="page.Shelf" placeholder="保质期（天）" style="width: 160px; margin-right: 8px;" />
        <el-input v-model="page.License" placeholder="生产许可证号" style="width: 160px; margin-right: 8px;" />
        <el-input v-model="page.Enterprise" placeholder="生产企业" style="width: 160px; margin-right: 8px;" />
        <el-input v-model="page.CreatreName" placeholder="创建人" style="width: 160px; margin-right: 8px;" />
        <el-input v-model="page.CreateTime" placeholder="创建时间" style="width: 160px; margin-right: 8px;" />
        <el-input v-model="page.UpdateName" placeholder="修改人" style="width: 160px; margin-right: 8px;" />
        <!-- 查询按钮 -->
        <el-button type="primary" @click="getDate()">查询</el-button>
      </el-col>
    </el-row>
    <!-- 数据表格 -->
    <el-table :data="tableData" border style="width: 100%" @selection-change="handleSelectionChange" ref="tableRef">
      <!-- 多选框列 -->
      <el-table-column type="selection" width="50" />
      <!-- 序号列 -->
      <el-table-column label="序号" type="index" width="60" />
      <!-- 主要数据列，prop 对应后端字段 -->
      <el-table-column v-if="visibleColumns.includes('goodsName')" prop="goodsName" label="商品名称" width="120" />
      <el-table-column v-if="visibleColumns.includes('batch')" prop="batch" label="生产批次" width="120" />
      <el-table-column v-if="visibleColumns.includes('shelf')" prop="shelf" label="保质期（天）" width="100" />
      <el-table-column v-if="visibleColumns.includes('license')" prop="license" label="生产许可证号" width="150" />
      <el-table-column v-if="visibleColumns.includes('enterprise')" prop="enterprise" label="生产企业" width="200" />
      <!-- 信息完善度，带颜色 -->
      <el-table-column v-if="visibleColumns.includes('completeness')" label="信息完善度" width="120">
        <template #default="scope">
          <span :style="{ color: getPercentColor(scope.row.completeness) }">
            {{ scope.row.completeness }}%
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="creatreName" label="创建人" width="120" />
      <el-table-column prop="createTime" label="创建时间" width="120" >
        <template #default="scope">
          {{ moment(scope.row.createTime).format("YYYY-MM-DD") }}
        </template>
      </el-table-column>
      <el-table-column prop="updateName" label="修改人" width="120" />
      <!-- 操作列 -->
      <el-table-column label="操作" width="260" fixed="right">
        <template #default="scope">
          <!-- 详情、修改、导出、删除等操作 -->
          <el-link type="primary" @click="handleDetail(scope.row)">详情</el-link>
          <el-link type="warning" @click="handleEdit(scope.row)" style="margin-left: 8px;">修改</el-link>
          <el-link type="success" @click="" style="margin-left: 8px;">导出溯源码</el-link>
          <el-link type="danger" @click="handleDel(scope.row.traceabilityId)" style="margin-left: 8px;">删除</el-link>
        </template>
      </el-table-column>
    </el-table>
    <!-- 列显示配置弹窗 -->
    <el-dialog v-model="showColumnConfig" title="列显示配置" width="400px">
      <el-checkbox-group v-model="visibleColumns">
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">{{ col.label }}</el-checkbox>
      </el-checkbox-group>
      <template #footer>
        <el-button @click="showColumnConfig = false">关闭</el-button>
      </template>
    </el-dialog>
    <!-- 添加弹窗-->
     <el-dialog v-model="dialogVisible" title="添加基本信息" width="500px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
        <el-form-item label="商品名称" prop="goodsId">
          <el-select v-model="form.goodsId" placeholder="请选择商品名称" filterable style="width: 100%">
            <el-option v-for="item in goods"  :label="item.goodsName" :value="item.goodsId" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入生产批次" />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="shelf">
          <el-input v-model="form.shelf" placeholder="请输入保质期" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="license">
          <el-input v-model="form.license" placeholder="请输入生产许可证号" />
        </el-form-item>
        <el-form-item label="生产企业" prop="enterprise">
          <el-input v-model="form.enterprise" placeholder="请输入生产企业" />
        </el-form-item>
        <el-form-item label="网成都" prop="completeness">
          <el-input v-model="form.completeness" placeholder="请输入生产企业" />
        </el-form-item>
         <el-form-item label="封面图" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5153/api/Traceability/UploadFile"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            
          >
          <!-- :before-upload="beforeCoverUpload" -->
            <img v-if="coverUrl" :src="coverUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
                </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitFormAdd()">保存</el-button>
            </template>
    </el-dialog> 
       <!-- 修改弹窗（已注释） -->
     <el-dialog v-model="isEdit" title="修改基本信息" width="500px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="110px">
        <el-form-item label="商品名称" prop="goodsId">
          <el-select v-model="form.goodsId" placeholder="请选择商品名称" filterable style="width: 100%">
            <el-option v-for="item in goods"  :label="item.goodsName" :value="item.goodsId" />
          </el-select>
        </el-form-item>
        <el-form-item label="生产批次" prop="batch">
          <el-input v-model="form.batch" placeholder="请输入生产批次" />
        </el-form-item>
        <el-form-item label="保质期（天）" prop="shelf">
          <el-input v-model="form.shelf" placeholder="请输入保质期" />
        </el-form-item>
        <el-form-item label="生产许可证号" prop="license">
          <el-input v-model="form.license" placeholder="请输入生产许可证号" />
        </el-form-item>
        <el-form-item label="生产企业" prop="enterprise">
          <el-input v-model="form.enterprise" placeholder="请输入生产企业" />
        </el-form-item>
        <el-form-item label="网成都" prop="completeness">
          <el-input v-model="form.completeness" placeholder="请输入生产企业" />
        </el-form-item>
        <el-form-item label="封面图" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5153/api/Traceability/UploadFile"
            :show-file-list="false"
            :on-success="handleCoverSuccess"
            
          >
          <!-- :before-upload="beforeCoverUpload" -->
            <img v-if="coverUrl" :src="coverUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="submitFormUpdate()">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// 引入 Vue 相关API
import { ref, reactive, onMounted, watch } from 'vue';
// 引入 Element Plus 组件和工具
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, Close } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import moment from 'moment';
import type { UploadProps } from 'element-plus'

// 表格ref
const tableRef = ref();
// 选中行数据
const selectedRows = ref([]);
// 弹窗相关

const currentEditRow = ref<any>(null);
const formRef = ref();

const coverFileList = ref([]);
const router = useRouter();
const breedImgs = ref<string[]>([]);
const showBreedDialog = ref(false);



//配置
// 列显示配置弹窗开关
const showColumnConfig = ref(false);
// 所有可配置列
const allColumns = [
  { prop: 'goodsName', label: '商品名称' },
  { prop: 'batch', label: '生产批次' },
  { prop: 'shelfLife', label: '保质期（天）' },
  { prop: 'license', label: '生产许可证号' },
  { prop: 'enterprise', label: '生产企业' },
  { prop: 'completeness', label: '信息完善度' },
];
// 当前显示的列
const visibleColumns = ref(allColumns.map(col => col.prop));
//显示查询
// 更多查询条件显示开关
const showMoreQuery = ref(false);
//查询参数对象
const page=reactive({
  GoodsName:'',
  Batch:'',
  Shelf:'',
  License:'',
  Enterprise:'',
  CreatreName:'',
  CreateTime:'',
  UpdateName:''
})
//表格数据
const tableData = ref([{
  "traceabilityId": 0,
      "goodsId": 0,
      "goodsName": "",
      "batch": "",
      "shelf": 0,
      "license": "",
      "enterprise": "",
      "completeness": 0,
      "cover": "0",
      "creatreName": "",
      "createTime": "2025-07-08T00:00:00",
      "updateName": ""
}]);
//获取表格数据（查询）
const getDate=()=>{
  axios.get("http://localhost:5153/api/Traceability/GetTraceability",{params:page}).then(res=>{
    tableData.value=res.data.data
  })
}
//页面加载时自动获取数据
onMounted(() => {
  const batch = localStorage.getItem('batch');
  if (batch) {
    // getDataBreed(batch); // This line was removed as per the new_code, as it's not directly related to Traceability.vue's batch handling.
    // breedForm.batch = batch; // This line was removed as per the new_code, as it's not directly related to Traceability.vue's batch handling.
    // breedInfo.value.batch = batch; // This line was removed as per the new_code, as it's not directly related to Traceability.vue's batch handling.
  }
  getDate()
  Getgoods();//商品下拉框
})
//监听
watch(page,()=>{
  getDate();
})
// 刷新
const shuxian=()=>{
  page. GoodsName='',
  page.Batch='',
  page.Shelf='',
  page.License='',
  page.Enterprise='',
  page.CreatreName='',
  page.CreateTime='',
  page.UpdateName=''
  getDate();
  ElMessage.success("刷新成功");
}

//选中行变化时触发
function handleSelectionChange(val: any) {
  selectedRows.value = val;
}
//跳转详情页
function handleDetail(row: any) {
  localStorage.setItem("batch",row.batch)
  localStorage.setItem("goodsName",row.goodsName)
  localStorage.setItem("shelf",row.shelf)
  localStorage.setItem("license",row.license)
  localStorage.setItem("enterprise",row.enterprise)
  localStorage.setItem("cover",row.cover)
  // 构造详情页需要的字段，保证字段名和 Details.vue 一致
  
  // const detailData = {
  //   goodsName: row.goodsName || '',
  //   batch: row.batch || '',
  //   shelf: row.shelf || '',
  //   license: row.license || '',
  //   enterprise: row.enterprise || '',
  //   cover: row.cover || '',
  // };

  router.push({
    name: 'Details',
    query: {  }
  });
}

//添加修改
const dialogVisible = ref(false);
const isEdit = ref(false);
// 表单数据
const form = reactive({
  "goodsId": '',
  "batch": "",
  "shelf": 0,
  "license": "",
  "enterprise": "",
  "completeness": 0,
  "cover": "",
  "creatreName": localStorage.getItem("userName"),
  "createTime": "",
  "updateName": localStorage.getItem("userName")
});
const rules = {
  goodsId: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
  batch: [{ required: true, message: '请输入生产批次', trigger: 'blur' }],
  shelf: [{ required: true, message: '请输入保质期', trigger: 'blur' }],
  license: [{ required: true, message: '请输入生产许可证号', trigger: 'blur' }],
  enterprise: [{ required: true, message: '请输入生产企业', trigger: 'blur' }],
  cover: [{ required: true, message: '请上传封面图', trigger: 'change' }],
};
//添加方法
const handleAdd=()=>{
  dialogVisible.value = true;
  form.batch = generateBatch(); // 自动生成批次号
}
const submitFormAdd=()=>{
  axios.post("http://localhost:5153/api/Traceability/AddTraceadility",form).then(res=>{
    if(res.data.code==200)
  {
    ElMessage.success(res.data.msg);
   
    
    form.goodsId='',
    form.batch='',
    form.shelf=0,
    form.license='',
    form.enterprise='',
    form.completeness=0,
    form.cover=''
    dialogVisible.value = false;
    getDate();
  }
  else{
    ElMessage.error(res.data.msg);
    getDate();
  }
  })
}
//商品下拉框
const goods=ref([{
  "goodsId": 0,
      "goodsName": ""
}])
const Getgoods=()=>{
  axios.get("http://localhost:5153/api/Goods/GetGoods",{params:goods.value}).then(res=>{
    goods.value=res.data.data
  })
}

//删除
const handleDel=(traceabilityId:any)=>{
 ElMessageBox.confirm(
    '确定删除吗?',
    '警告',
    {
      confirmButtonText: '确实',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      axios.get("http://localhost:5153/api/Traceability/DelTraceadility?TraceabilityId="+traceabilityId).then(res=>{
        if(res.data.code==200)
      {
        ElMessage.success(res.data.msg);
        getDate();
      }
      else
      {
        ElMessage.error(res.data.msg);

      }
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '删除被取消',
      })
    })
}
//修改操作
const handleEdit=(row: any) =>{
  isEdit.value = true;
  Object.assign(form,row)
  coverUrl.value = getFullCoverUrl(row.cover); // 反填图片
}
const submitFormUpdate=()=>{
  axios.post("http://localhost:5153/api/Traceability/UpdateTraceadility",form).then(res=>{
   if(res.data.code==200)
  {
    ElMessage.success(res.data.msg);
    isEdit.value = false;
    getDate();
  }
  else{
    ElMessage.error(res.data.msg);
    getDate();
  }
  })
}



//上传前校验 图片
function beforeBreedUpload(file: File) {
  const isImage = file.type.startsWith('image/');
  if (!isImage) {
    ElMessage.error('只能上传图片文件');
    return false;
  }
  if (breedImgs.value.length >= 9) {
    ElMessage.error('最多上传9张图片');
    return false;
  }
  return true;
}
//处理图片上传
//上传图片
const formLabelWidth = '50px'
const coverUrl = ref('')
function getFullCoverUrl(cover:any) {
  if (!cover) return '';
  if (/^https?:\/\//.test(cover)) return cover;
  if (cover.startsWith('/')) return cover;
  return `/img/${cover}`;
}
const handleCoverSuccess: UploadProps['onSuccess'] = (response) => {
  coverUrl.value = getFullCoverUrl(response.data);
  form.cover = response.data;
}

// const beforeCoverUpload: UploadProps['beforeUpload'] = (rawFile) => {
//   if (rawFile.type !== 'image/jpeg') {
//     ElMessage.error('封面图必须是 JPG 格式!')
//     return false
//   } else if (rawFile.size / 1024 / 1024 > 2) {
//     ElMessage.error('封面图大小不能超过 2MB!')
//     return false
//   }
//   return true
// }
//删除图片
function removeBreedImg(idx: number) {
  breedImgs.value.splice(idx, 1);
}
// 生成批次号，格式为YYYYMMDD
function generateBatch() {
  const now = new Date();
  const y = now.getFullYear();
  const m = String(now.getMonth() + 1).padStart(2, '0');
  const d = String(now.getDate()).padStart(2, '0');
  const s=String(now.getSeconds()).padStart(2,'0')
  return `${y}${m}${d}${s}`;
}
//信息完善度颜色
function getPercentColor(completeness: number) {
  if (completeness === 100) return 'green';
  if (completeness >= 80) return 'orange';
  return 'red';
}
</script>

<style scoped>
.img-list {
  display: flex;
  align-items: center;
  gap: 12px;
  flex-wrap: wrap;
}

.img-item {
  position: relative;
  width: 80px;
  height: 80px;
}

.img-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #eee;
}

.img-delete {
  position: absolute;
  top: -10px;
  right: -10px;
  background: #fff;
  border-radius: 50%;
  color: #f56c6c;
  font-size: 20px;
  cursor: pointer;
  border: 1px solid #eee;
  z-index: 2;
}

.upload-btn {
  width: 80px;
  height: 80px;
  border: 1px dashed #d9d9d9;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  cursor: pointer;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
